using Senparc.Weixin.Exceptions;
using Senparc.Weixin.MP.Entities;
using System;
using System.Collections.Generic;
namespace Senparc.Weixin.MP.CommonAPIs
{
	public class JsApiTicketContainer
	{
		private static Dictionary<string, JsApiTicketBag> JsApiTicketCollection = new Dictionary<string, JsApiTicketBag>(StringComparer.OrdinalIgnoreCase);
		public static void Register(string appId, string appSecret)
		{
			JsApiTicketContainer.JsApiTicketCollection[appId] = new JsApiTicketBag
			{
				AppId = appId,
				AppSecret = appSecret,
				ExpireTime = DateTime.MinValue,
				JsApiTicketResult = new JsApiTicketResult()
			};
		}
		public static string TryGetTicket(string appId, string appSecret, bool getNewTicket = false)
		{
			if (!JsApiTicketContainer.CheckRegistered(appId) || getNewTicket)
			{
				JsApiTicketContainer.Register(appId, appSecret);
			}
			return JsApiTicketContainer.GetTicket(appId, false);
		}
		public static string GetTicket(string appId, bool getNewTicket = false)
		{
			return JsApiTicketContainer.GetTicketResult(appId, getNewTicket).ticket;
		}
		public static JsApiTicketResult GetTicketResult(string appId, bool getNewTicket = false)
		{
			if (!JsApiTicketContainer.JsApiTicketCollection.ContainsKey(appId))
			{
				throw new WeixinException("此appId尚未注册，请先使用JsApiTicketContainer.Register完成注册（全局执行一次即可）！");
			}
			JsApiTicketBag jsApiTicketBag = JsApiTicketContainer.JsApiTicketCollection[appId];
			lock (jsApiTicketBag.Lock)
			{
				if (getNewTicket || jsApiTicketBag.ExpireTime <= DateTime.Now)
				{
					jsApiTicketBag.JsApiTicketResult = CommonApi.GetTicket(jsApiTicketBag.AppId, jsApiTicketBag.AppSecret, "jsapi");
					jsApiTicketBag.ExpireTime = DateTime.Now.AddSeconds((double)jsApiTicketBag.JsApiTicketResult.expires_in);
				}
			}
			return jsApiTicketBag.JsApiTicketResult;
		}
		public static bool CheckRegistered(string appId)
		{
			return JsApiTicketContainer.JsApiTicketCollection.ContainsKey(appId);
		}
	}
}
